package com.codejoys.framework;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Framework {
    private Map<String, String> config = new HashMap<>();

    public Framework(String configName) {
        //读取配置文件，加载数据库连接信息
        //得到资源文件的uri(资源文件的定位路径)
        URI uri = null;
        try {
            uri = getClass().getClassLoader().getResource(configName).toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        try {
            List<String> strings = Files.readAllLines(Paths.get(uri));
            System.out.println(strings);

            for (String line : strings) {
                String[] split = line.split("=");
                config.put(split[0], split[1]);
//                System.out.println("Key:"+split[0]+"#"+"value:"+split[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Connection openConnection() {
        //加载驱动
        try {
            Class.forName(config.get("jdbc.driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //获取连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    config.get("jdbc.url"),
                    config.get("jdbc.username"),
                    config.get("jdbc.password")
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

}
